package com.informationsystem.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.informationsystem.service.AttachementManager;
import com.informationsystem.service.DepartmentManager;
import com.informationsystem.service.NoticeManager;
import com.informationsystem.service.SystemuserManager;
import com.informationsystem.dao.SearchException;
import com.informationsystem.model.Attachement;
import com.informationsystem.model.Department;
import com.informationsystem.model.Notice;
import com.informationsystem.webapp.action.BaseAction;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;

public class NoticeAction extends BaseAction implements Preparable {
    private NoticeManager noticeManager;
    private DepartmentManager departmentManager;
	private AttachementManager attachementManager;
    private List notices;
    private Notice notice;
    private Long id;
    private String query;
    private Date hourformat;
    private File attachmentfile;
    private String contentType;
    private String filename;
    private List<File> uploads = new ArrayList<File>();
    private List<String> uploadFileNames = new ArrayList<String>();
    private List<String> uploadContentTypes = new ArrayList<String>();
    private Long attachmentid;
    
    public void setNoticeManager(NoticeManager noticeManager) {
        this.noticeManager = noticeManager;
    }

    public List getNotices() {
        return notices;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String noticeId = getRequest().getParameter("notice.id");
            if (noticeId != null && !noticeId.equals("")) {
                notice = noticeManager.get(new Long(noticeId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        try {
            notices = noticeManager.search(query, Notice.class);
        } catch (SearchException se) {
            addActionError(se.getMessage());
            notices = noticeManager.getAll();
        }
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Notice getNotice() {
        return notice;
    }

    public void setNotice(Notice notice) {
        this.notice = notice;
    }

    public String delete() {
    	notice = noticeManager.get(notice.getId());
    	for(Attachement a: notice.getAttachements()){
        	File file = new File(ServletActionContext.getServletContext().getRealPath("/upload")+"\\"+notice.getId()+"_" + a.getFilename());
        	file.delete();
    	}
        noticeManager.remove(notice.getId());
        addLog("delete notice id:" +notice.getId() + " title: "+ notice.getTitle());
        saveMessage(getText("notice.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            notice = noticeManager.get(id);
        } else {
            notice = new Notice();
            notice.setSystemuser(getLoginUser());
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (notice.getId() == null);
        
        //Add attachment to notice
        if(isNew){
        	for(int i=0;i<uploads.size();i++){
        		if(uploads.get(i)!=null){
        			Attachement attachement = new Attachement();
        	    	attachement.setFilename(uploadFileNames.get(i));
        	    	attachement.setNotice(notice);
        			notice.getAttachements().add(attachement);
        		}
        	}
        }
        
        if(!isNew)
        	notice.setPostDate(generatePostDate());
        else
        	notice.setPostDate(new Date());
        
        notice = noticeManager.save(notice);
        
        //copy attachment file
        if(isNew){
        	for(int i=0;i<uploads.size();i++){
        		if(uploads.get(i)!=null){
        			saveFile(notice.getId()+"_"+uploadFileNames.get(i), uploads.get(i));
        		}
        	}
        }
        
        String key = (isNew) ? "notice.added" : "notice.updated";
        saveMessage(getText(key));
        
        if(!isNew){
        	addLog("edit notice id:" +notice.getId() + " title: "+ notice.getTitle());
        }
        else{
        	addLog("add notice id:" +notice.getId() + " title: "+ notice.getTitle());
        }
        
        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
    
    public String addAttachment(){
    	if(attachmentfile==null)
    		return SUCCESS;
    	Attachement attachement = new Attachement();
    	attachement.setFilename(filename);
    	attachement.setNotice(notice);
    	notice = noticeManager.get(notice.getId());
    	notice.getAttachements().add(attachement);
    	noticeManager.save(notice);
        try {
			saveFile(notice.getId()+"_"+filename, attachmentfile);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return SUCCESS;
    }
    
    public void saveFile(String tosavefilename, File tosavefile) throws IOException{
		String path = ServletActionContext.getServletContext().getRealPath("/upload");
		File f = new File(path);
        if(!f.exists()){
            f.mkdir(); 
        }     
        FileOutputStream fos = new FileOutputStream(ServletActionContext.getServletContext().getRealPath("/upload")+"\\"+tosavefilename);
        InputStream is = new FileInputStream(tosavefile);
        byte[] buffer = new byte[8192];
        int count = 0;
        while ((count = is.read(buffer)) > 0) {
            fos.write(buffer, 0, count);
    	}
        fos.flush();
    	fos.close();
    	is.close();
    }
    public String deleteAttachment(){
    	Attachement attachement = attachementManager.get(getAttachmentid());
    	attachementManager.remove(attachement.getId());
    	File file = new File(ServletActionContext.getServletContext().getRealPath("/upload")+"\\"+notice.getId()+"_" + attachement.getFilename());
    	file.delete();
    	return SUCCESS;
    }
    
	public DepartmentManager getDepartmentManager() {
		return departmentManager;
	}

	public void setDepartmentManager(DepartmentManager departmentManager) {
		this.departmentManager = departmentManager;
	}
	
	public List getDepartmentList(){
		return departmentManager.getAll();
	}

	public SystemuserManager getSystemuserManager() {
		return systemuserManager;
	}

	public void setSystemuserManager(SystemuserManager systemuserManager) {
		this.systemuserManager = systemuserManager;
	}
	
	public List getSystemuserList(){
		return systemuserManager.getAll();
	}

	public Date getHourformat() {
		return notice.getPostDate();
	}

	public void setHourformat(Date hourformat) {
		this.hourformat = hourformat;
	}
	
	@SuppressWarnings("deprecation")
	public Date generatePostDate(){
		Calendar cal = Calendar.getInstance();
		cal.setTime(notice.getPostDate()); 
		cal.set(Calendar.HOUR_OF_DAY, hourformat.getHours());
		cal.set(Calendar.MINUTE,hourformat.getMinutes());

		return cal.getTime();
	}

	public File getAttachmentfile() {
		return attachmentfile;
	}

	public void setAttachmentfile(File attachmentfile) {
		this.attachmentfile = attachmentfile;
	}
	

    public void setAttachmentfileContentType(String contentType) {
       this.contentType = contentType;
    }

    public void setAttachmentfileFileName(String filename) {
       this.filename = filename;
    }

	public AttachementManager getAttachementManager() {
		return attachementManager;
	}

	public void setAttachementManager(AttachementManager attachementManager) {
		this.attachementManager = attachementManager;
	}

	public Long getAttachmentid() {
		return attachmentid;
	}

	public void setAttachmentid(Long attachmentid) {
		this.attachmentid = attachmentid;
	}
	
	public List<File> getUpload() {
	        return this.uploads;
	}
	public void setUpload(List<File> uploads) {
	    this.uploads = uploads;
	}
	
	public List<String> getUploadFileName() {
	    return this.uploadFileNames;
	}
	public void setUploadFileName(List<String> uploadFileNames) {
	    this.uploadFileNames = uploadFileNames;
	}
	
	public List<String> getUploadContentType() {
	    return this.uploadContentTypes;
	}
	public void setUploadContentType(List<String> contentTypes) {
	    this.uploadContentTypes = contentTypes;
	}
}